package com.bonc.web.user;

import com.bonc.pojo.SysUser;
import com.bonc.service.ISysUserService;
import com.bonc.util.exception.BusinessException;
import com.bonc.util.response.CommResponseEnum;
import com.bonc.util.string.StringUtils;
import com.bonc.util.validate.ValidateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Description: 用户登录验证
 * @Author: ChenZhiXiang
 * @CreateDate: 2019/3/1 0001 15:12
 * @Version: 1.0
 */
@Component
public class SysLoginService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysPasswordService sysPasswordService;

    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    public SysUser login(String userName, String password) throws Exception {
        // 用户名或密码不能为空
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            logger.info("用户或密码不能为空");
            throw new BusinessException(CommResponseEnum.USER4);
        }
        //匹配小写字母、大写字母、数字、特殊符号的两种及两种以上【非中文】，长度8到16位
        if (!ValidateUtil.isPassword(userName,password)){
            logger.info("密码长度大于8位小于16位，必须包含字母、数字、特殊字符，且不能包含用户名!");
            throw new BusinessException(CommResponseEnum.USER3);
        }
        // 用户名不在指定范围内
        if (userName.length() < UserConstants.USERNAME_MIN_LENGTH
                || userName.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            logger.info("用户名2-20");
            throw new BusinessException(CommResponseEnum.USER1);
        }
        SysUser user = iSysUserService.getUserByUsername(userName);
        // 用户为空
        if (StringUtils.isNull(user)){
            logger.info("用户不存在");
            throw new BusinessException(CommResponseEnum.USER5);
        }
        // 用户是否已删除
        if (UserStatus.DELETE.getCode().equals(user.getDelFlag()))
        {
            logger.info("用户已删除");
            throw new BusinessException(CommResponseEnum.USER6);
        }
        // 用户是否已被锁定
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            logger.info("用户已锁定");
            throw new BusinessException(CommResponseEnum.USER7);
        }
        // 校验密码
        sysPasswordService.validate(user,password);
        return user;
    }
}
